package db.mongodb;

import com.mongodb.*;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.Map;
import java.util.Set;

public class MongoDBConnectUtil {

    /**
     * 简单查询案例
     */
    public static void main(String[] args) {
        //获取客户端连接
        MongoClient mongoClient = getMongoDbClient("ip地址", 27018, "database", "username", "password");
        //获取指定数据库的集合
        MongoCollection<Document> collection = getMongoDbCollection(mongoClient.getDatabase("database"), "集合名称");

        //创建查询条件
        BasicDBObject findDbObject = new BasicDBObject();
        findDbObject.put("key1", new BasicDBObject("$gt", "H.3303775")); //key1 > H.3303775
        //$gt：>
        //$gte：>=
        //$eq: =
        //$ne: !=
        //$lt: <
        //$lte: <=
        //$in: in(后面的值为bson对象数组)
        //$nin: not in(后面的值为bson对象数组)

        BasicDBObject sortDbObject = new BasicDBObject();
        sortDbObject.put("key2", 1); //根据 key2 升序
        //1: 升序
        //-1: 降序

        //查询
        FindIterable<Document> result = collection.find(findDbObject).sort(sortDbObject).limit(10000);

        //遍历结果集
        MongoCursor<Document> cursor = result.iterator();
        Document document = null;
        int i = 0;
        while (cursor.hasNext()) {
            document = cursor.next();
            Set<Map.Entry<String, Object>> set = document.entrySet();
            for (Map.Entry<String, Object> entry : set) {
                System.out.println(entry.getKey() + "---->" + entry.getValue());
            }
            System.out.println("-----------------------" + (i++) + "--------------------------");
        }

        //关闭客户端连接
        mongoClient.close();
    }


    /**
     * 获取指定的集合
     */
    public static MongoCollection<Document> getMongoDbCollection(MongoDatabase mongoDatabase, String collection){
        return mongoDatabase.getCollection(collection);
    }

    /**
     * 获取 MongoDB 连接客户端
     * @param ip ip地址
     * @param port 端口号
     * @return
     */
    public static MongoClient getMongoDbClient(String ip, int port, String database, String username, String password){
        //获取身份验证凭据
        MongoCredential credential = MongoCredential.createCredential(username, database, password.toCharArray());
        //获取连接配置
        MongoClientOptions options = MongoClientOptions.builder().build();
        //获取客户端连接
        MongoClient mongoClient = new MongoClient(new ServerAddress(ip, port), credential, options);

        return mongoClient;
    }
}
